const {
  findData,
  addData,
  delData,
  updateData,
  code,
} = require("./db");

// 这边通过async方法保证数据的同步获取

let query = async (ctx, sql, config = {}) => {
  // 获取数据
  let { params, type = "json", isObj } = config;
  // 返回的数据格式为json
  ctx.response.type = type;
  await findData(sql, params).then((data) => {
    ctx.body = {
      data: isObj ? data[0] : data,
      msg: "查询成功",
      code: code.success,
    };
  });
};

let add = async (ctx, sql, config = {}) => {
  // 添加数据
  // console.log(ctx)
  let { params, type = "json" } = config;
  ctx.response.type = type;
  console.log(params);
  await addData(sql, params).then(
    (data) => {
      ctx.body = data;
    },
    () => {
      ctx.body = data;
    }
  );
};

let del = async (ctx, sql, config = {}) => {
  // 删除数据
  let { params, type = "json" } = config;
  ctx.response.type = type;
  await delData(sql, params).then(
    (data) => {
      ctx.body = data;
    },
    () => {
      ctx.body = data;
    }
  );
};

let update = async (ctx, sql, config = {}) => {
  // 修改数据
  let { params, type = "json", msg = "更新成功" } = config;
  ctx.response.type = type;
  await updateData(sql, params).then((data) => {
    // console.log(data)
    ctx.body = {
      data: null,
      msg,
      code: code.success,
    };
  });
};

module.exports = {
  query,
  add,
  del,
  update
};


